package org.come.baitan;

import com.tool.Stall.Commodity;
import com.tool.Stall.Stall;
import com.tool.role.RoleData;
import com.tool.tcpimg.UIUtils;
import org.come.bean.LoginResult;
import org.come.entity.Goodstable;
import org.come.entity.RoleSummoning;
import org.come.until.*;

import javax.swing.*;
import java.awt.*;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.font.FontRenderContext;
import java.awt.font.LineBreakMeasurer;
import java.awt.font.TextAttribute;
import java.awt.font.TextLayout;
import java.awt.geom.Rectangle2D;
import java.math.BigDecimal;
import java.text.AttributedCharacterIterator;
import java.text.AttributedString;
import java.util.ArrayList;
import java.util.List;

/**
 * @author 式
 * @version 1.0
 * @project test1
 * @description 购买窗口
 * @date 2024/1/30 20:49:23
 */
public class GouMaiJpanel extends JPanel {
    ImageIcon back = new ImageIcon("inkImg/btsg/购买者视角-查看出售-道具.png");
    ImageIcon back1 = new ImageIcon("inkImg/btsg/收购者视角-查看收购.png");
    ImageIcon back2 = new ImageIcon("inkImg/btsg/交易记录界面.png");
    public JScrollPane scrollPane;
    public JPanel jPanel;
    public static Commodity good;
    public static RoleSummoning pet;
    public static ShouGou shougou;
    public JTextField pice;
    public JTextField shuliang;
    public JTextField name;
    public BaiTanBtn goumai;
    public int id = -1;
    public BaiTanBtn[] xuanxiangka = new BaiTanBtn[3];
    public BaiTanBtn[] goodandpet = new BaiTanBtn[2];
    public static ImageIcon img;
    public static ImageIcon path1;
    public List<MyJpanel> myJpanels = new ArrayList<>();
    public JScrollPane goumaijilu;
    public goumaijilu goumaijilujpanel = new goumaijilu(new ArrayList<>());
    public JScrollPane shougoujilu;
    public goumaijilu shougoujilujpanel = new goumaijilu(new ArrayList<>());

    public GouMaiJpanel() {
        this.setPreferredSize(new Dimension(688, 488));
        this.setLayout(null);
        this.setOpaque(false);
        jPanel = new JPanel();
        jPanel.setLayout(null);
        scrollPane = new JScrollPane(jPanel);
        scrollPane.getVerticalScrollBar().setUI(new SrcollPanelUI());
        this.scrollPane.getViewport().setOpaque(false);
        this.scrollPane.setOpaque(false);
        this.scrollPane.setBounds(48, 78, 610, 335);
        this.scrollPane.setBorder(null);
        this.scrollPane.setHorizontalScrollBarPolicy(31);
        this.add((Component) this.scrollPane);
        this.pice = new JTextField();
        this.pice.setBounds(200, 450, 130, 20);
        this.pice.setForeground(Color.white);
        this.pice.setBackground(Color.WHITE);
        this.pice.setBorder(BorderFactory.createEmptyBorder());
        this.pice.setCaretColor(Color.WHITE);
        this.pice.setOpaque(false);
        this.pice.setEnabled(false);
        this.pice.setFont(UIUtils.TEXT_FONT1);
        this.add((Component) this.pice);
        this.shuliang = new JTextField();
        this.shuliang.setBounds(200, 422, 130, 20);
        this.shuliang.setForeground(Color.white);
        this.shuliang.setBackground(Color.WHITE);
        this.shuliang.setBorder(BorderFactory.createEmptyBorder());
        this.shuliang.setCaretColor(Color.WHITE);
        this.shuliang.setOpaque(false);
        this.shuliang.setFont(UIUtils.TEXT_FONT1);
        this.add(shuliang);
        BaiTanJpanel.allowNumericOnly(shuliang);
        BaiTanJpanel.allowNumericOnly(pice);
        this.name = new JTextField() {
            @Override
            public void paint(Graphics g) {
                super.paint(g);
            }
        };
        this.name.setBounds(340, 20, 130, 20);
        this.name.setForeground(Color.white);
        this.name.setBackground(Color.WHITE);
        this.name.setBorder(BorderFactory.createEmptyBorder());
        this.name.setCaretColor(Color.WHITE);
        this.name.setOpaque(false);
        this.name.setFont(UIUtils.TEXT_FONT1);
        this.name.setEnabled(false);
        this.add(name);
        goumai = new BaiTanBtn("inkImg/btsg/购买按钮.png", 1, UIUtils.HLW, UIUtils.Black, "购买", this, 100);
        goumai.setBounds(550, 437, 79, 25);
        this.add(goumai);
        xuanxiangka[0] = new BaiTanBtn("inkImg/btsg/上方按钮-选中.png", 1, UIUtils.HLW, UIUtils.Black, "出售", this, 101);
        xuanxiangka[0].setBounds(50, 20, 85, 33);
        this.add(xuanxiangka[0]);
        xuanxiangka[1] = new BaiTanBtn("inkImg/btsg/上方按钮-未选中.png", 1, UIUtils.HLW, UIUtils.Black, "收购", this, 102);
        xuanxiangka[1].setBounds(50 + 88, 20, 85, 33);
        this.add(xuanxiangka[1]);
        xuanxiangka[2] = new BaiTanBtn("inkImg/btsg/上方按钮-未选中.png", 1, UIUtils.HLW, UIUtils.Black, "交易记录", this, 103);
        xuanxiangka[2].setBounds(50 + 88 * 2, 20, 85, 33);
        this.add(xuanxiangka[2]);
        goodandpet[0] = new BaiTanBtn("inkImg/btsg/售卖类别按钮-未选中.png", 1, UIUtils.TEXT_FONT1, UIUtils.Black, "道具", this, 104);
        goodandpet[0].setBounds(50, 55, 90, 24);
        this.add(goodandpet[0]);
        goodandpet[1] = new BaiTanBtn("inkImg/btsg/售卖类别按钮-未选中.png", 1, UIUtils.TEXT_FONT1, UIUtils.Black, "宠物", this, 105);
        goodandpet[1].setBounds(150, 55, 90, 24);
        this.add(goodandpet[1]);
        for (int i = 0; i < 10; i++) {
            MyJpanel myJpanel = new MyJpanel(null);
            myJpanel.setOpaque(false);
            myJpanel.setPreferredSize(new Dimension(50, 50));
            myJpanel.setBounds(50 + i * 61, 355, 50, 50);
            myJpanel.setVisible(false);
            this.add(myJpanel);
            myJpanels.add(myJpanel);
        }
        (this.goumaijilu = new JScrollPane((Component) this.goumaijilujpanel)).setVerticalScrollBarPolicy(22);
        this.goumaijilu.getVerticalScrollBar().setUI(new SrcollPanelUI());
        this.goumaijilu.getViewport().setOpaque(false);
        this.goumaijilu.setOpaque(false);
        this.goumaijilu.setBounds(45, 75, 303, 280);
        this.goumaijilu.setBorder(null);
        this.goumaijilu.setHorizontalScrollBarPolicy(31);
        this.add((Component) this.goumaijilu);
        (this.shougoujilu = new JScrollPane((Component) this.shougoujilujpanel)).setVerticalScrollBarPolicy(22);
        this.shougoujilu.getVerticalScrollBar().setUI(new SrcollPanelUI());
        this.shougoujilu.getViewport().setOpaque(false);
        this.shougoujilu.setOpaque(false);
        this.shougoujilu.setBounds(45 + 305, 75, 303, 280);
        this.shougoujilu.setBorder(null);
        this.shougoujilu.setHorizontalScrollBarPolicy(31);
        this.add((Component) this.shougoujilu);
    }

    public int petandgood = -1;

    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        goodandpet[0].setBounds(50, 52, 90, 24);
        goodandpet[1].setBounds(143, 52, 90, 24);
        goumaijilu.setVisible(false);
        shougoujilu.setVisible(false);
        if (id == 0) {
            name.setBounds(340, 20, 130, 20);
            g.drawImage(back.getImage(), 0, 0, 687, 487, null);
            pice.setText("");
            if (shuliang.getText() == null || shuliang.getText().equals("")) {
                if (petandgood == 1)
                    shuliang.setText(0 + "");
                else shuliang.setText(1 + "");
            } else {
                if (petandgood == 1)
                    shuliang.setText(String.valueOf(Long.parseLong(shuliang.getText())));
                else shuliang.setText("1");
            }
            LoginResult loginResult = RoleData.getRoleData().getLoginResult();
            Util.drawPrice(g, new BigDecimal(loginResult.getGold().longValue()), 370, 467);
            if (good != null && good.getGood() != null && petandgood == 1) {
                g.drawImage(GoodsListFromServerUntil.imgpath(good.getGood().getSkin()).getImage(), 100, 425, 45, 45, null);
                if (Long.parseLong(shuliang.getText()) >= good.getNumber()) {
                    shuliang.setText(good.getNumber() + "");
                }
                Util.drawPrice(g, new BigDecimal(good.getMoney() * Long.parseLong(shuliang.getText())), 370, 437);
                Util.drawPrice(g, new BigDecimal(good.getMoney()), 200, 467);
            } else if (good != null && good.getPet() != null && petandgood == 2) {
                g.drawImage(GoodsListFromServerUntil.imgpath(good.getGood().getSkin()).getImage(), 100, 425, 45, 45, null);
                Util.drawPrice(g, new BigDecimal(good.getMoney() * Long.parseLong(shuliang.getText())), 370, 437);
                Util.drawPrice(g, new BigDecimal(good.getMoney()), 200, 467);
                shuliang.setText("1");
                g.drawImage(img.getImage(), 105, 430, 35, 35, null);
                g.drawImage(path1.getImage(), 102, 425, 45, 45, null);
            }
        } else if (id == 1) {
            g.drawImage(back1.getImage(), 0, 0, 687, 487, null);
            name.setBounds(430, 20, 130, 20);
            LoginResult loginResult = RoleData.getRoleData().getLoginResult();
            Util.drawPrice(g, new BigDecimal(loginResult.getGold().longValue()), 370, 467);
            pice.setText("");
            if (shuliang.getText() == null || shuliang.getText().equals("")) {
                shuliang.setText(0 + "");
            } else shuliang.setText(Long.parseLong(shuliang.getText()) + "");

            if (shougou != null) {
                g.drawImage(GoodsListFromServerUntil.imgpath(shougou.getGoodstable().getSkin()).getImage(), 100, 425, 45, 45, null);
                Goodstable ltrGoods = getGoodType(shougou.goodstable.getGoodsid().longValue());
                int num = ltrGoods == null ? 0 : ltrGoods.getUsetime();
                if (num <= Long.parseLong(shuliang.getText())) {
                    shuliang.setText(num + "");
                }
                Util.drawPrice(g, new BigDecimal(shougou.getPice()), 200, 467);
                Util.drawPrice(g, new BigDecimal(shougou.getPice() * Long.parseLong(shuliang.getText())), 370, 437);
            }
            for (int i = 0; i <= myJpanels.size() - 1; i++) {
                myJpanels.get(i).setBounds(50 + i * 61, 355, 50, 50);
            }
        } else if (id == 2) {
            name.setBounds(340, 20, 130, 20);
            g.drawImage(back2.getImage(), 0, 0, 687, 487, null);
            goumaijilu.setVisible(true);
            shougoujilu.setVisible(true);
        }


    }

    public static Goodstable getGoodType(long type) {
        Goodstable[] goodslist = GoodsListFromServerUntil.getGoodslist();
        Goodstable goodstable = null;
        int i = 0;

        for (int len = goodslist.length; i < len; ++i) {
            if (goodslist[i] != null && goodslist[i].getGoodsid().longValue() == type) {
                goodstable = goodslist[i];
                break;
            }
        }
        return goodstable;
    }

    public List<Goodstable> goodstableList = new ArrayList<>();
    public List<RoleSummoning> roleSummonings = new ArrayList<>();
    public Stall stall;

    public void updateLabels(Stall stall, int id, int petandgood, boolean p) {
        if (p) {
            this.id = id;
            this.petandgood = petandgood;
        }

        // 清空已有的JLabel
        this.stall = stall;
        name.setText(stall.getStall());
        jPanel.removeAll();
        jPanel.setOpaque(false);
        this.scrollPane.setBounds(48, 78, 610, 335);
        scrollPane.setVisible(true);
        for (int i = 0; i <= myJpanels.size() - 1; i++) {
            {
                myJpanels.get(i).setVisible(false);
                myJpanels.get(i).setShouGou(null);
            }
        }
        // 动态添加新的JLabel
        int totalWidth = 0;
        int totalHeight = 0;
        if (id == 0) {
            if (petandgood == 1) {
                List<Goodstable> roleSummonings = new ArrayList<>();
                for (int i = 0; i <= stall.getGoodstables().length - 1; i++) {
                    if (stall.getGoodstables()[i] == null) continue;
                    if (stall.getGoodstables()[i].getNumber() <= 0) continue;
                    if (stall.getGoodstables()[i].getGood().getRgid() == null) continue;
                    roleSummonings.add(stall.getGoodstables()[i].getGood());

                }
                for (int i = 0; i <= roleSummonings.size() - 1; i++) {//
                    Goodstable roleSummoning = roleSummonings.get(i);
                    Commodity commodity = null;
                    for (int k = 0; k <= stall.getGoodstables().length - 1; k++) {
                        if (stall.getGoodstables()[k] == null) continue;
                        if (stall.getGoodstables()[k].getNumber() <= 0) continue;
                        if (stall.getGoodstables()[k].getGood().getRgid() == null) continue;
                        if (stall.getGoodstables()[k].getGood().getRgid().longValue() == roleSummoning.getRgid().longValue()) {
                            commodity = stall.getGoodstables()[k];
                        }
                    }
                    MaiGoodsJpanel label = new MaiGoodsJpanel(commodity, new ImageIcon("inkImg/btsg/道具信息框.png"), 1, 148, 53);
                    int k = i / 4;
                    int j = i % 4;
                    label.setBounds(152 * (j), 2 + k * 57, 148, 53);
                    jPanel.add(label);

                }
                totalWidth = 152 * 4;
                totalHeight = (jPanel.getComponentCount() / 4 + 1) * 57;
            } else if (petandgood == 2) {
                List<RoleSummoning> roleSummonings = new ArrayList<>();
                for (int i = 0; i <= stall.getPets().length - 1; i++) {
                    if (stall.getPets()[i] == null) continue;
                    if (stall.getPets()[i].getNumber() <= 0) continue;
                    if (stall.getPets()[i].getPet().getSid() == null) continue;
                    roleSummonings.add(stall.getPets()[i].getPet());

                }
                for (int i = 0; i <= roleSummonings.size() - 1; i++) {
                    RoleSummoning roleSummoning = roleSummonings.get(i);
                    Commodity commodity = null;
                    for (int k = 0; k <= stall.getPets().length - 1; k++) {
                        if (stall.getPets()[k] == null) continue;
                        if (stall.getPets()[k].getNumber() <= 0) continue;
                        if (stall.getPets()[k].getPet().getSid() == null) continue;
                        if (stall.getPets()[k].getPet().getSid().longValue() == roleSummoning.getSid().longValue()) {
                            commodity = stall.getPets()[k];
                        }
                    }
                    MaiGoodsJpanel label = new MaiGoodsJpanel(commodity, new ImageIcon("inkImg/btsg/召唤兽信息框.png"), 2, 300, 76);
                    int k = i / 2;
                    int j = i % 2;
                    label.setBounds(304 * (j), 2 + k * 78, 300, 76);

                    jPanel.add(label);

                }
                totalWidth = 304 * 4;
                totalHeight = (jPanel.getComponentCount() / 4 + 1) * 57;
            }

        } else if (id == 1) {
            this.scrollPane.setBounds(48, 78, 610, 245);
            List<Goodstable> goodstableList = new ArrayList<>();
            if (stall.getShouGous() != null)
                for (ShouGou shouGou : stall.getShouGous()) {
                    if (shouGou == null || shouGou.num == 0) continue;
                    goodstableList.add(shouGou.goodstable);
                }
            for (int i = 0; i <= goodstableList.size() - 1; i++) {
                for (ShouGou shouGou : stall.getShouGous()) {
                    if (shouGou.goodstable.getGoodsid().longValue() == goodstableList.get(i).getGoodsid().longValue()) {
                        MaiGoodsJpanel label = new MaiGoodsJpanel(shouGou, new ImageIcon("inkImg/btsg/收购.png"), 3, 198, 54);
                        int k = i / 3;
                        int j = i % 3;
                        label.setBounds(202 * (j), 2 + k * 54, 198, 54);
                        if (i <= 9) {
                            myJpanels.get(i).setShouGou(shouGou);
                        }
                        jPanel.add(label);
                    }
                }
            }
            for (int i = 0; i <= myJpanels.size() - 1; i++) {
                if (myJpanels.get(i).getShouGou() == null) {
                    myJpanels.get(i).setVisible(false);
                }
            }
            totalWidth = 202 * 4;
            totalHeight = (jPanel.getComponentCount() / 4 + 2) * 57;
        } else if (id == 2) {
            this.scrollPane.setVisible(false);
        }

        jPanel.setPreferredSize(new Dimension(totalWidth, totalHeight));
        // 重新绘制Panel
        jPanel.revalidate();
        jPanel.repaint();
    }

    public static class MyJpanel extends JPanel {
        ShouGou shouGou;
        private boolean isSelected = false;
        ImageIcon imageIcon = new ImageIcon("inkImg/btsg/border_quack.png");

        MyJpanel(ShouGou shouGou) {
            this.shouGou = shouGou;
            this.setOpaque(false);
            this.setPreferredSize(new Dimension(50, 50));
            this.addMouseListener(new MouseListener() {
                @Override
                public void mouseClicked(MouseEvent e) {
                    updateSelectedState();
                    isSelected = !isSelected; // 切换选中状态
                    repaint();


                }

                @Override
                public void mousePressed(MouseEvent e) {

                }

                @Override
                public void mouseReleased(MouseEvent e) {
                    FormsManagement.HideForm(46);
                }

                @Override
                public void mouseEntered(MouseEvent e) {


                }

                @Override
                public void mouseExited(MouseEvent e) {

                }
            });

        }

        private void updateSelectedState() {
            // 遍历所有兄弟面板，重置选中状态
            Container parent = getParent();
            if (parent instanceof JPanel) {
                Component[] components = ((JPanel) parent).getComponents();
                for (Component component : components) {
                    if (component instanceof MyJpanel && component != this) {
                        ((MyJpanel) component).isSelected = false;
                        GouMaiJpanel.shougou = shouGou;
                    }
                }
            }
        }

        @Override
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            //	g.drawImage(imageIcon.getImage(),0,0,50,50,null);
            if (this.shouGou != null) {

                g.drawImage(GoodsListFromServerUntil.imgpath(shouGou.getGoodstable().getSkin()).getImage(), 0, 3, 45, 45, null);
            }
            if (this.shouGou == null) return;
            Goodstable ltrGoods = getGoodType(this.shouGou.goodstable.getGoodsid().longValue());
            int num = ltrGoods == null ? 0 : ltrGoods.getUsetime();
            if (num != 0) {
                g.setColor(Color.white);
                g.drawString(num + "", 2, 10);
            }

            if (isSelected) {
                g.setColor(Color.RED);
                g.drawRect(0, 0, getWidth() - 1, getHeight() - 1);
            }
        }

        public ShouGou getShouGou() {
            return shouGou;
        }

        public void setShouGou(ShouGou shouGou) {
            this.shouGou = shouGou;
        }
    }

    public static class goumaijilu extends JPanel {
        public List<Record> records;

        goumaijilu(List<Record> records) {
            this.records = records;
            this.setOpaque(false);
            this.setPreferredSize(new Dimension(303, 280));
        }

        @Override
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            Graphics2D g2d = (Graphics2D) g;

            // 设置字体
            Font font = new Font("宋体", Font.PLAIN, 15);

            g2d.setFont(font);
            g2d.setColor(Color.yellow);
            // 设置绘制区域
            int width = getWidth();
            int height = getHeight();
            int margin = 10; // 你可以调整边距
            Rectangle2D rect = new Rectangle2D.Double(margin, margin, width - 2 * margin, height - 2 * margin);

            // 绘制文本
            float y = (float) rect.getY() + font.getSize();
            for (Record record : records) {
                String text = recordToString(record);
                //g.drawString(text,0,10);
                drawWrappedText(g2d, text, rect.getX() - 10, y - 20, rect.getWidth());
                y += font.getSize() * 2.2; // 你可以调整行间距
            }
            repaint();
        }

        private void drawWrappedText(Graphics2D g2d, String text, double x, double y, double maxWidth) {
            FontRenderContext frc = g2d.getFontRenderContext();
            AttributedString attributedString = new AttributedString(text);
            attributedString.addAttribute(TextAttribute.FONT, g2d.getFont());

            AttributedCharacterIterator paragraph = attributedString.getIterator();
            LineBreakMeasurer lineBreakMeasurer = new LineBreakMeasurer(paragraph, frc);
            float drawPosY = (float) y;

            while (lineBreakMeasurer.getPosition() < paragraph.getEndIndex()) {
                TextLayout layout = lineBreakMeasurer.nextLayout((float) maxWidth);
                drawPosY += layout.getAscent();
                layout.draw(g2d, (float) x, drawPosY);
                drawPosY += layout.getDescent() + layout.getLeading();
            }
        }

        public List<Record> getRecords() {
            return records;
        }

        public void setRecords(List<Record> records) {
            this.records = records;
        }
    }

    public static String recordToString(Record record) {

        if (record.getRecordType() == 100) {
            return "玩家" + record.getRoleid() + "花费了" + record.getText() + "购买了" + record.getGoodsum() + "个" + UserMessUntil.getgoodstable(new BigDecimal(record.getGoodsid())).getGoodsname() + "。" + "(" + record.getRecordTime() + ")";
        } else if (record.getRecordType() == 101) {
            return "店铺花费了" + record.getText() + "收购了玩家" + record.getRoleid() + record.getGoodsum() + "个" + UserMessUntil.getgoodstable(new BigDecimal(record.getGoodsid())).getGoodsname() + "。" + "(" + record.getRecordTime() + ")";
        }
        return null;
    }
}
